#!/usr/bin/perl

use strict;
use warnings;
use JSON;
use Test::Differences;
use Test::Builder;
use Test::Deep;

my $e4e_test = Test::Builder->new;

sub enc_json { eval { JSON->new->utf8->pretty->encode(@_) } };
sub dec_json { eval { JSON->new->utf8->pretty->decode(@_) } };

sub diff_req($$$$) {
	my ( $servant, $func, $req, $resp ) = @_;

	my $http_resp = dancer_response POST => "/$servant", {
		body => enc_json {
			func => $func,
			arg => $req
		},
	};

	my $server_resp = dec_json $http_resp->{content};

	$e4e_test->ok( $http_resp->{status} == 200, "接口[$func] 预期http返回码200 实际[$http_resp->{status}]" ) and
	$e4e_test->ok( $server_resp->{ret} == 0, "接口[$func] 预期业务返回码0 实际[$server_resp->{ret}]" ) and
	$e4e_test->ok( eq_or_diff($server_resp->{data}, $resp), "返回格式匹配" );
}

sub deeply_req($$$$) {
	my ( $servant, $func, $req, $resp ) = @_;

	my $http_resp = dancer_response POST => "/$servant", {
		body => enc_json {
			func => $func,
			arg => $req
		},
	};

	my $server_resp = dec_json $http_resp->{content};

	$e4e_test->ok( $http_resp->{status} == 200, "接口[$func] 预期http返回码200 实际[$http_resp->{status}]" ) and
	$e4e_test->ok( $server_resp->{ret} == 0, "接口[$func] 预期业务返回码0 实际[$server_resp->{ret}]" ) and
	$e4e_test->ok( cmp_deeply ($server_resp->{data}, $resp, '格式匹配'), "返回格式匹配" );
}
